<?php
/********************************************************/
/* Module Name: addnewcase.php						    */
/* Description: add new case into casereferred table */
/* Written by: Maria Cielo Carreno							*/
/********************************************************/

 // creates the new record form
 // since this form is used multiple times in this file, I have made it a function that is easily reusable
 //variables
 //Array designation
 /*
 0=>case no
 1=>plaintiff
 2=>plaintiff lawyer
 3=>defendant
 4=>defendant lawyer
 5=>nature of case
 6=>judge
 7=>active
 8=>hearing date
 9=>mediator
 10=>comments
 11=>mediation status
 */
 session_start();
//If your session isn't valid, it returns you to the login screen for protection
if(empty($_SESSION['myusername'])){
 header("location:main_login.php");
}
if(empty($_SESSION['seedval'])){
 header("location:main_login.php");
}
//echo $_SESSION['myusername'];
if($_GET['id'] != $_SESSION['seedval'])
{
	echo 'Security breakage!';
	$error = 1;
}
if(isset($_GET['caseno']))
{
	$caseno=$_GET['caseno'];
}
else 
 header("location:main_login.php");
 
define("IDS",1);
 
 //$newCaseArray = array('','','','','','','','','','','','');
 function GetTypeCase()
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM typeofcase Order by Tdescription") 
                or die(mysql_error());  
		$select = "<select name=\"typeofcase\">\n<option></option>\n";
		while($row = mysql_fetch_array( $result ))
		{
			$select .="\t<option>".$row['Tdescription']."   *".$row['typeId']."</option>\n";
		}
		$select .= "</select>";
		echo $select;
 }
 
 
 function GetNatureCase()
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM natureofcase Order by Ndescription") 
                or die(mysql_error());  
		$select = "<select name=\"natureofcase\">\n<option></option>\n";
		while($row = mysql_fetch_array( $result ))
		{
			$select .="\t<option>".$row['Ndescription']."   *".$row['code']."</option>\n";
		}
		$select .= "</select>";
		echo $select;
 }
 
 function GetMediator()
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM mediator Order by mediatorName") 
                or die(mysql_error());  
		$select = "<select name=\"mediatorname\">\n<option></option>";
		while($row = mysql_fetch_array( $result ))
		{
			$select .="\t<option>".$row['mediatorName']."   *".$row['mediatorId']."</option>\n";
		}
		$select .= "</select>";
		echo $select;
 }
 
 function GetJudge()
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM judges Order by referringJudge") 
                or die(mysql_error());  
		$select = "<select name=\"judgename\">\n<option></option>";
		while($row = mysql_fetch_array( $result ))
		{
			   $select .="\t<option>".$row['referringJudge']."   *".$row['judgeId']."</option>\n";
		}
		$select .= "</select>";
		echo $select;
 }
 
 function DateSelect()
 {
	$curr_month = date("m");
	$curr_day = date("d");
	$curr_year = date("Y");
	$month = array (1=>"Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec ");
	$day_today = range(1,31);
	$year = range(1900,2020);
	//show month selection
	$select = "<select name=\"month\">\n";
	foreach ($month as $key => $val) {
		$select .= "\t<option val=\"".$key."\"";
		if ($key == $curr_month) {
			$select .= " selected=\"selected\">".$val."</option>\n";
		} else {
			$select .= ">".$val."</option>\n";
		}
	}
	$select .= "</select>";
	echo $select;
	//show day selection
	$select = "<select name=\"day\">\n";
	foreach ($day_today as $key => $val) {
		$select .= "\t<option val=\"".$key."\"";
		if ($val == $curr_day) {
			$select .= " selected=\"selected\">".$val."</option>\n";
		} else {
			$select .= ">".$val."</option>\n";
		}
	}
	$select .= "</select>";
	echo $select;
	//show year selection
	$select = "<select name=\"year\">\n";
	foreach ($year as $key => $val) {
		$select .= "\t<option val=\"".$key."\"";
		if ($val == $curr_year) {
			$select .= " selected=\"selected\">".$val."</option>\n";
		} else {
			$select .= ">".$val."</option>\n";
		}
	}
	$select .= "</select>";
	echo $select;	
 }
 
 function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

 function successwindow()
 {
 ?>
	<html>
	<head>
	<link href="default.css" rel="stylesheet" type="text/css" />
	</head>
	<body>
	<div id="fulladmin">
	<div id="simple">
	<center><h1>Mediatrix Database</h1><br>
	<form  action="dashboard.php" method="get">
	<div style="padding:4px; border:0px solid red; color:red;" align="center">Saved! Please click the button to continue..</div>
	<center> <input type="submit" value="Continue" /> <center>
	</form>
	</div>
	</div>
	</body>
	</html>
<?php
 }
 
 function renderForm(&$newCaseArr,$error)
 {
// print_r($newCaseArr);
 
 
 ?>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <link href="default.css" rel="stylesheet" type="text/css" />
 <title>Open New Case</title>
 </head>
 <body>
 <div id="fulladmin">
 
 <center><h1>Add New Case</h1><br>
 <center><h2>Case Information</h2>
 <table border='0' cellpadding='10'>
   <tr><th>
 <?php


 // if there are any errors, display them
 if ($error != '')
 {
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
 }
 ?> 
 
 <form action="" method="post">
 <div align='left'>
 <table border="0">
  <tr><td><strong>Case Number:     </strong> </td><td><input type="text" name="caseno" value="<?php echo $newCaseArr['caseno']; ?>" readonly='readonly'/></td></tr>
  <tr><td><strong>Unit Control #: </strong> </td><td><input type="text" name="controlID" value="<?php echo $newCaseArr['controlID']; ?> " /> </td></tr>
 <!-- <tr><td><strong>Case Title:     </strong> </td><td><input type="text" name="casetitle" value="<?php echo $newCaseArr['casetitle']; ?>" /></td></tr> -->
 <tr><td><strong>Plaintiff Name:  </strong> </td><td><input type="text" name="plaintiffname" value="<?php echo $newCaseArr['plaintiffname']; ?>" /></td></tr>
 <!-- <tr><td><strong>Plaintiff Lawyer:</strong> </td><td><input type="text" name="plaintifflawyer" value="<?php echo $newCaseArr['plaintifflawyer']; ?>" /></td></tr> -->
 <tr><td><strong>Defendant Name:  </strong> </td><td><input type="text" name="defendantname" value="<?php echo $newCaseArr['defendantname']; ?>" /></td></tr>
 <!-- <tr><td><strong>Defendant Lawyer:</strong> </td><td><input type="text" name="defendantlawyer" value="<?php echo $newCaseArr['defendantlawyer']; ?>" /></td></tr> -->
 <tr><td><strong>Nature of Case:  </strong> </td><td><?php GetNatureCase(); ?></td></tr>
 <tr><td><strong>Type of Case:  </strong> </td><td><?php GetTypeCase(); ?></td></tr>
 <tr><td><strong>Judge Name:      </strong> </td><td><?php GetJudge(); ?></td></tr>
 <tr><td><strong>Active:</strong></td><td>
 <select name="casestatus">
	<option value="Yes" selected="selected">Yes</option>
	<option value="No" >No</option>
</select></td></tr></table><br>

<center><h2>Hearing Schedule and Mediator</h2></center>
 <table border="0" align = "left">
 <tr><td><strong>Date (mm/dd/yyyy):</strong> </td><td><?php DateSelect(); ?></td></tr>
  <tr><td><strong>Mediator:</strong> </td><td><?php GetMediator(); ?></td></tr>
  <tr><td><strong>Comments: (type comments)</strong></td><td>
		<textarea rows="5" cols="20" wrap="physical" name="comments"></textarea></td></tr>
 <tr><td><strong>Mediation status:</strong></td><td>
<select name="mediationstatus">
	<option value="Ongoing" selected="selected">On Going</option>
	<option value="failed" >Failed</option>
	<option value="settled">Settled</option>
<!--	<option value="backtocourt" >Back to court</option> -->
</select></td></tr>
<tr><td></td><td>
 <center>
 <input type="submit" name="submit" value="Submit">
 <input type="submit" name="back" value="Back">
  </center></td></tr></table> </th></tr></table>
 </div></div>
 </form> 
 </div>
 <div id="body"></div>
 <div id="footer"><center>Return to main <a href="dashboard.php"><font color="red">Dashboard</font></a>, or you can <a href="log_out.php?id=<?php echo $_SESSION['userid'];?>"><font color="red">Log Out</font></a></center></div>

 </body>
 </html>
 <?php 
 }
 
 
 

 // connect to the database
 include('connect-db.php');
 
 // check if the form has been submitted. If it has, start to process the form and save it to the database
 if (isset($_POST['submit']))
 { 
 // get form data, making sure it is valid
	$ucno = mysql_real_escape_string(htmlspecialchars($_POST['controlID']));
	$caseno = mysql_real_escape_string(htmlspecialchars($_POST['caseno']));
	//$casetitle = mysql_real_escape_string(htmlspecialchars($_POST['casetitle']));
	$plaintiffname = mysql_real_escape_string(htmlspecialchars($_POST['plaintiffname']));
	//$plaintifflawyer = mysql_real_escape_string(htmlspecialchars($_POST['plaintifflawyer']));
	$defendantname = mysql_real_escape_string(htmlspecialchars($_POST['defendantname']));
	//$defendantlawyer = mysql_real_escape_string(htmlspecialchars($_POST['defendantlawyer']));
	$natureofcase = mysql_real_escape_string(htmlspecialchars($_POST['natureofcase']));
	$typeofcase = mysql_real_escape_string(htmlspecialchars($_POST['typeofcase']));
	$judgename = mysql_real_escape_string(htmlspecialchars($_POST['judgename']));
	$mediatorname = mysql_real_escape_string(htmlspecialchars($_POST['mediatorname']));
	$month = mysql_real_escape_string(htmlspecialchars($_POST['month']));
	$day = mysql_real_escape_string(htmlspecialchars($_POST['day']));
	$year = mysql_real_escape_string(htmlspecialchars($_POST['year']));
	$casestatus = mysql_real_escape_string(htmlspecialchars($_POST['casestatus']));
	$mediationstatus = mysql_real_escape_string(htmlspecialchars($_POST['mediationstatus']));
	$comments = mysql_real_escape_string(htmlspecialchars($_POST['comments']));
	
	//---date conversion----
	$datestring = $month." ".$day." ".$year;
	$tm = strtotime($datestring);
	$hearingdate = date('Y-m-d',$tm);
	//echo $hearingdate;
	//datelog
	$today = date('Y-m-d');
	//echo $today;
	

	if ($caseno == '' || $judgename == '' || $mediatorname=='' || $ucno == '')
	{
	// generate error message
		$error = 'ERROR: Please fill in all required fields!';
 
	// if either field is blank, display the form again
	//$newCaseArray = $_POST;
	//print_r ($newCaseArray);
// for debugging only
		$i=0;
		foreach ($_POST as $var => $value) { 
			$newCaseArray[$i] = $value;
		//echo "new case =$newCaseArray[$i]<br>";
		//echo "$var = $value<br>"; 
			$i++;
		} 
	    //print_r ($newCaseArray);
		
		renderForm($_POST,$error);
	}
	else
	{
	//-- get Ids for mediator,nature of case, type of case and judge--
		$judgeselect = explode("*",$judgename);
		$mediatorselect = explode("*",$mediatorname);
		$typeofcaseselect = explode("*",$typeofcase);
		$natureofcaseselect = explode("*",$natureofcase);
		
		//echo $judgeselect[IDS];
	
	 // connect to the database
    include('connect-db.php');
	// verify case first the database
	$sql_script = 'SELECT * FROM casereferred WHERE CaseNo="'.$caseno.'"';

    $result = mysql_query($sql_script)
				or die(mysql_error()); 

    $row = mysql_num_rows($result);

	
		if($row>0){
			$error = 'ERROR: Case No.'.$caseno.' already exist!';
			renderForm($newCaseArray,$error);
		}
		else{
		//add new case to casereferred table
		  //  $sql_script = "INSERT INTO casereferred (CaseNo,typeId,caseTitle,natureOfCase,judgeId,mediatorId,dateRegister,plaintiffName,plaintiffLawyer,defendantName,defendantLawyer,caseStatus) ";
		//	$sql_script .="VALUES('".$caseno."',".$typeofcaseselect[IDS].",'".$casetitle."',".$natureofcaseselect[IDS].",".$judgeselect[IDS].",".$mediatorselect[IDS].",'".$today."','".$plaintiffname."','";
		 $sql_script = "INSERT INTO casereferred (controlID,CaseNo,typeId,natureOfCase,judgeId,mediatorId,dateRegister,plaintiffName,defendantName,caseStatus) ";
		 $sql_script .="VALUES('".$ucno."','".$caseno."',".$typeofcaseselect[IDS].",".$natureofcaseselect[IDS].",".$judgeselect[IDS].",".$mediatorselect[IDS].",'".$today."','".$plaintiffname."','";
    	 $sql_script .= $defendantname."','".$casestatus."')";
		//	echo $sql_script;
		//	exit;
			
			mysql_query($sql_script)
			or die(mysql_error()); 
		//Add schedule
			$sql_script = "INSERT INTO schedule (CaseNo,Date,status,Comments) VALUES('".$caseno."','".$hearingdate."','".$mediationstatus."','".$comments."')";
			mysql_query($sql_script)
			or die(mysql_error()); 
			
			successwindow();
		}
	// once saved, redirect back to the view page
		//header("Location: dashboard.php"); 
	}
 }
 else
 // if the form hasn't been submitted, display the form
 {
  $error = '';
    if(isset($_POST['back']))
	   header("Location: dashboard.php");
	else{
	   $newCaseArr=array("controlID" => "",
						 "caseno" => $caseno,
						 "plaintiffname"=>"",
						 "defendantname"=>"");
	   renderForm($newCaseArr,$error);
	 }
 }
?> 